/**
 * 全局通用JavaScript函数 - Bootstrap 5版本
 */

// API基础URL
const API_BASE_URL = '/api';

// 通用工具函数
const Utils = {
    
    // 格式化日期
    formatDate(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    },
    
    // 格式化日期时间
    formatDateTime(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN');
    },
    
    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },
    
    // 节流函数
    throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        }
    },
    
    // 深拷贝对象
    deepClone(obj) {
        return JSON.parse(JSON.stringify(obj));
    },
    
    // 验证邮箱格式
    isValidEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    },
    
    // 验证手机号格式
    isValidPhone(phone) {
        const re = /^1[3-9]\d{9}$/;
        return re.test(phone);
    },
    
    // 生成随机ID
    generateId() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    }
};

// HTTP请求工具
const Http = {
    
    // 添加当前用户信息到请求参数
    _addUserInfo(params = {}) {
        const currentUser = localStorage.getItem('currentUser');
        if (currentUser) {
            // 确保不覆盖已有的user_id参数
            if (!params.user_id) {
                params.user_id = currentUser;
            }
        }
        return params;
    },
    
    // GET请求
    async get(url, params = {}) {
        // 添加用户信息
        params = this._addUserInfo(params);
        
        const queryString = new URLSearchParams(params).toString();
        const fullUrl = queryString ? `${url}?${queryString}` : url;
        
        try {
            const response = await fetch(fullUrl);
            return await response.json();
        } catch (error) {
            throw new Error(`请求失败: ${error.message}`);
        }
    },
    
    // POST请求
    async post(url, data = {}) {
        // 添加用户信息
        data = this._addUserInfo(data);
        
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });
            return await response.json();
        } catch (error) {
            throw new Error(`请求失败: ${error.message}`);
        }
    },
    
    // PUT请求
    async put(url, data = {}) {
        // 添加用户信息
        data = this._addUserInfo(data);
        
        try {
            const response = await fetch(url, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });
            return await response.json();
        } catch (error) {
            throw new Error(`请求失败: ${error.message}`);
        }
    },
    
    // DELETE请求
    async delete(url, params = {}) {
        // 添加用户信息
        params = this._addUserInfo(params);
        
        // 将参数添加到URL
        const queryString = new URLSearchParams(params).toString();
        const fullUrl = queryString ? `${url}?${queryString}` : url;
        
        try {
            const response = await fetch(fullUrl, {
                method: 'DELETE'
            });
            return await response.json();
        } catch (error) {
            throw new Error(`请求失败: ${error.message}`);
        }
    },
    
    // 文件上传
    async upload(url, formData) {
        // 添加用户信息到FormData
        const currentUser = localStorage.getItem('currentUser');
        if (currentUser && !formData.has('user_id')) {
            formData.append('user_id', currentUser);
        }
        
        try {
            const response = await fetch(url, {
                method: 'POST',
                body: formData
            });
            return await response.json();
        } catch (error) {
            throw new Error(`上传失败: ${error.message}`);
        }
    }
};

// 表单验证工具
const Validator = {
    
    // 验证必填字段
    required(value, message = '此字段为必填项') {
        if (!value || (typeof value === 'string' && !value.trim())) {
            return message;
        }
        return null;
    },
    
    // 验证最小长度
    minLength(value, min, message = `最少需要${min}个字符`) {
        if (value && value.length < min) {
            return message;
        }
        return null;
    },
    
    // 验证最大长度
    maxLength(value, max, message = `最多允许${max}个字符`) {
        if (value && value.length > max) {
            return message;
        }
        return null;
    },
    
    // 验证数字范围
    range(value, min, max, message = `值必须在${min}到${max}之间`) {
        const num = parseFloat(value);
        if (!isNaN(num) && (num < min || num > max)) {
            return message;
        }
        return null;
    },
    
    // 验证表单
    validateForm(formData, rules) {
        const errors = {};
        
        for (const field in rules) {
            const fieldRules = rules[field];
            const value = formData[field];
            
            for (const rule of fieldRules) {
                const error = rule(value);
                if (error) {
                    errors[field] = error;
                    break;
                }
            }
        }
        
        return {
            isValid: Object.keys(errors).length === 0,
            errors: errors
        };
    }
};

// 本地存储工具
const Storage = {
    
    // 设置localStorage
    set(key, value) {
        try {
            localStorage.setItem(key, JSON.stringify(value));
        } catch (error) {
            console.error('localStorage设置失败:', error);
        }
    },
    
    // 获取localStorage
    get(key, defaultValue = null) {
        try {
            const item = localStorage.getItem(key);
            return item ? JSON.parse(item) : defaultValue;
        } catch (error) {
            console.error('localStorage获取失败:', error);
            return defaultValue;
        }
    },
    
    // 删除localStorage
    remove(key) {
        try {
            localStorage.removeItem(key);
        } catch (error) {
            console.error('localStorage删除失败:', error);
        }
    },
    
    // 清空localStorage
    clear() {
        try {
            localStorage.clear();
        } catch (error) {
            console.error('localStorage清空失败:', error);
        }
    }
};

// 认证工具
const Auth = {
    // 检查用户是否已登录
    isLoggedIn() {
        return localStorage.getItem('isLoggedIn') === 'true';
    },
    
    // 获取当前登录用户
    getCurrentUser() {
        return localStorage.getItem('currentUser');
    },
    
    // 退出登录
    logout() {
        localStorage.removeItem('isLoggedIn');
        localStorage.removeItem('currentUser');
        window.location.href = 'login.html';
    },
    
    // 检查登录状态，未登录则跳转到登录页面
    checkLoginStatus() {
        // 如果当前不是登录页面，且未登录，则跳转到登录页面
        if (!window.location.pathname.includes('login.html') && !this.isLoggedIn()) {
            window.location.href = 'login.html';
            return false;
        }
        return true;
    }
};

// 导出到全局作用域
window.Utils = Utils;
window.Http = Http;
window.Validator = Validator;
window.Storage = Storage;
window.Auth = Auth;

// 在非登录页面执行登录检查
if (!window.location.pathname.includes('login.html')) {
    document.addEventListener('DOMContentLoaded', function() {
        Auth.checkLoginStatus();
    });
}